# langchain框架实现代理---Agents
# 代理就是一种用大语言模型做出决策、调用工具来执行具体操作的系统。通过设定代理的性格、背景以及工具的描述，你可以定制代理的行为，使其能够根据输入的文本做出理解和推理，从而实现自动化的任务处理。

import os
import warnings
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.agents import tool
from datetime import date

warnings.filterwarnings("ignore")

api_key = "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"
os.environ['OPENAI_API_KEY'] = "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"
# 初始化语言模型
chat = ChatOpenAI(api_key=api_key, temperature=0)
# 加载工具（LLM数学工具、维基百科）
tools = load_tools(["llm-math", "wikipedia"], llm=chat)

def get_langchain_agent_openai():
    # 初始化代理
    agent = initialize_agent(
        tools,
        chat,
        agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
        handle_parsing_errors=True,
        verbose=True)
    question1 = "What is the 25% of 300?"
    result1 = agent(question1)

    question2 = "Tom M. Mitchell is an American computer scientist \
    and the Founders University Professor at Carnegie Mellon University (CMU)\
    what book did he write?"
    result2 = agent(question2)


@tool
def time(text: str) -> str:
    """Returns todays date, Use the format yyyy-mm-dd,use this for any \
    questions related to knowing todays date. \
    The input should always be an empty string, \
    and this function will always return todays \
    date - any date mathmatics should occur \
    outside this function."""
    return str(date.today())
def get_langchain_own_tool():
    agent = initialize_agent(
        tools + [time],
        chat,
        agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
        handle_parsing_errors=True,
        verbose=True)
    try:
        result = agent("whats the date today?")
    except:
        print("exception on external access")

if __name__ == '__main__':
    get_langchain_own_tool()